package org.example.gateway;

import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

//@Configuration
public class GatewayFlowRulesConfig {

    @PostConstruct
    public void init() {
        Set<ApiDefinition> definitions = new HashSet<>();
        ApiDefinition api = new ApiDefinition("my_group")
                .setPredicateItems(Collections.singleton(
                        new ApiPathPredicateItem().setPattern("/consume/**")
                ));
        definitions.add(api);
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);

        // 2. 再针对分组做流控
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("my_group")
                .setCount(1)
                .setIntervalSec(1)
                .setBurst(0));
        GatewayRuleManager.loadRules(rules);
    }
}